package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRelation;
import com.atguigu.gulimall.product.vo.GroupWithAttrs;
import com.atguigu.gulimall.product.vo.SpuGroupName;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private AttrService attrService;
    @Autowired
    private AttrAttrgroupRelationService relationService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageWithCondition(Map<String, Object> params, Long catelogId) {
        IPage<AttrGroupEntity> page = null;
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(item -> {
                item.eq("attr_group_id", key)
                        .or().like("attr_group_name", params.get("key"));
            });
        }
        if (catelogId == 0) {
            //查询所有属性分组
            //封装分页属性和排序属性
            page = new Query<AttrGroupEntity>().getPage(params);
            //分页查询所有数据
            this.page(page, wrapper);

        } else {
            //根据条件查询
            page = new Query<AttrGroupEntity>().getPage(params);
            wrapper.eq("catelog_id", catelogId);
            this.page(page, wrapper);
        }
        return new PageUtils(page);
    }

    @Override
    public AttrGroupEntity setCategoryPath(AttrGroupEntity attrGroup) {
        List<Long> path = new ArrayList<>();

        List<Long> catPath = getParent(attrGroup.getCatelogId(), path);
        Collections.reverse(catPath);
        attrGroup.setCatelogPath(catPath);
        return attrGroup;
    }

    /**
     * 根据分组id查询所有属性
     *
     * @param attrgroupId 分组id
     * @return 所有基础属性数组
     */
    @Override
    public List<AttrEntity> RelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<AttrEntity> attrEntities = null;
        if(relationEntities!=null&&relationEntities.size()>0){
            List<Long> attrIds =
                    relationEntities.stream().map(item ->
                            item.getAttrId()).collect(Collectors.toList());
             attrEntities = (ArrayList)attrService.listByIds(attrIds);
        }
        return attrEntities;
    }

    @Transactional
    @Override
    public void DeleteRelation( List<AttrRelation> relations) {
        List<AttrAttrgroupRelationEntity> list=
        relations.stream().map(item->{
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item,relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        //调用关联表的mapper
        relationService.deleteByBatch(list);
    }

    /**
     * 根据分类id查询所有分组以及其所关联的属性
     * @param catelogId
     * @return
     */
    @Override
    public List<GroupWithAttrs> getGroupWithAttrs(Long catelogId) {
        //查询所有的分组
        List<AttrGroupEntity> groups = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds =
                groups.stream().map(item->
                item.getAttrGroupId()).collect(Collectors.toList());
        List<AttrGroupEntity> groupEntities = (ArrayList)attrGroupService.listByIds(groupIds);

        List<GroupWithAttrs> groupWithAttrs =
        groupEntities.stream().map(item->{
            GroupWithAttrs groupWithAttr = new GroupWithAttrs();
            BeanUtils.copyProperties(item,groupWithAttr);
            //查询所关联的属性
            List<AttrEntity> attrs = attrService.getRelationAttr(groupWithAttr.getAttrGroupId());
            groupWithAttr.setAttrs(attrs);
            return groupWithAttr;
        }).collect(Collectors.toList());
        return groupWithAttrs;
    }

    @Override
    public List<SpuGroupName> getGroupWithAttrsBySpuId(Long catalogId, Long spuId) {
        List<SpuGroupName> groupNames = this.baseMapper.getGroupWithAttrsBySpuId(catalogId,spuId);
        return groupNames;
    }

    public List<Long> getParent(Long catId, List<Long> path) {
        path.add(catId);
        CategoryEntity category = categoryService.getById(catId);
        if (category.getParentCid() != null && category.getParentCid() != 0L) {
            getParent(category.getParentCid(), path);
        }
        return path;
    }
}